/**
 * 模拟消息处理器 - 仅用于测试
 */

import { 
  ChatMessage, 
  ChatResponse, 
  StreamingResponse, 
  NodeType, 
  TurnStatus, 
  ChatMode 
} from '../../types';
import { MessageProcessor } from '../../message-broker';

export class MockMessageProcessor implements MessageProcessor {
  private responseDelay: number;
  private chunkDelay: number;
  private shouldFail: boolean;

  constructor(options: {
    responseDelay?: number;
    chunkDelay?: number;
    shouldFail?: boolean;
  } = {}) {
    this.responseDelay = options.responseDelay ?? 100;
    this.chunkDelay = options.chunkDelay ?? 50;
    this.shouldFail = options.shouldFail ?? false;
  }

  async processMessage(message: ChatMessage, options: any): Promise<ChatResponse> {
    if (this.shouldFail) {
      throw new Error('Mock processing failed');
    }

    // 模拟处理延迟
    await this.delay(this.responseDelay);

    return {
      id: this.generateId(),
      content: `Mock response to: ${message.content}`,
      role: 'assistant',
      timestamp: new Date(),
      state: TurnStatus.Success,
      metadata: {
        mode: options.mode || ChatMode.CHAT,
        processingTime: this.responseDelay,
        mock: true
      }
    };
  }

  async *processStreamingMessage(
    message: ChatMessage, 
    options: any
  ): AsyncIterable<StreamingResponse> {
    if (this.shouldFail) {
      yield {
        type: 'error',
        error: 'Mock streaming failed'
      };
      return;
    }

    // 开始思考节点
    yield {
      type: 'node',
      node: {
        type: NodeType.Thinking,
        content: 'Mock: Processing your request...',
        metadata: { mock: true }
      }
    };

    await this.delay(200);

    // 原始响应节点 - 分块发送
    const responseText = `Mock streaming response to: ${message.content}`;
    for (let i = 0; i < responseText.length; i += 5) {
      const chunk = responseText.slice(i, i + 5);
      yield {
        type: 'node',
        node: {
          type: NodeType.RawResponse,
          content: chunk,
          metadata: { mock: true }
        }
      };

      await this.delay(this.chunkDelay);
    }

    // 主文本完成节点
    yield {
      type: 'node',
      node: {
        type: NodeType.MainTextFinished,
        content: '',
        metadata: { mock: true }
      }
    };

    // 建议问题节点
    yield {
      type: 'node',
      node: {
        type: NodeType.SuggestedQuestions,
        content: JSON.stringify([
          'Mock: Can you explain more about this?',
          'Mock: What are the alternatives?',
          'Mock: How can I implement this?'
        ]),
        metadata: { mock: true }
      }
    };

    // 状态更新
    yield {
      type: 'state',
      state: TurnStatus.Success
    };
  }

  // 测试辅助方法
  setShouldFail(shouldFail: boolean): void {
    this.shouldFail = shouldFail;
  }

  setResponseDelay(delay: number): void {
    this.responseDelay = delay;
  }

  setChunkDelay(delay: number): void {
    this.chunkDelay = delay;
  }

  private delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  private generateId(): string {
    return `mock_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
  }
}
